package com.vehiclesecure.service;

import com.vehiclesecure.model.User;
import com.vehiclesecure.model.Vehicle;
import com.vehiclesecure.repository.VehicleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

/**
 * 车辆信息服务层
 * 处理车辆信息的业务逻辑
 */
@Service
public class VehicleService {

    private final VehicleRepository vehicleRepository;
    private final UserService userService;
    private final VehicleUserSyncService vehicleUserSyncService;

    @Autowired
    public VehicleService(VehicleRepository vehicleRepository, 
                         UserService userService,
                         VehicleUserSyncService vehicleUserSyncService) {
        this.vehicleRepository = vehicleRepository;
        this.userService = userService;
        this.vehicleUserSyncService = vehicleUserSyncService;
    }

    /**
     * 创建新车辆
     * @param vehicle 车辆信息
     * @return 创建的车辆
     */
    @Transactional
    public Vehicle createVehicle(Vehicle vehicle) {
        // 验证VIN码和车牌号的唯一性
        if (vehicleRepository.existsByVin(vehicle.getVin())) {
            throw new RuntimeException("VIN码已存在: " + vehicle.getVin());
        }
        
        if (vehicleRepository.existsByLicensePlate(vehicle.getLicensePlate())) {
            throw new RuntimeException("车牌号已存在: " + vehicle.getLicensePlate());
        }
        
        // 设置默认值
        if (vehicle.getId() == null) {
            vehicle.setId(UUID.randomUUID().toString());
        }
        
        if (vehicle.getCreatedAt() == null) {
            vehicle.setCreatedAt(LocalDateTime.now());
        }
        
        if (vehicle.getUpdatedAt() == null) {
            vehicle.setUpdatedAt(LocalDateTime.now());
        }
        
        if (vehicle.getStatus() == null) {
            vehicle.setStatus(Vehicle.Status.ACTIVE.name());
        }
        
        if (vehicle.getIsActive() == null) {
            vehicle.setIsActive(true);
        }
        
        if (vehicle.getIsStolen() == null) {
            vehicle.setIsStolen(false);
        }
        
        if (vehicle.getMileage() == null) {
            vehicle.setMileage(0);
        }
        
        // 保存车辆
        Vehicle savedVehicle = vehicleRepository.save(vehicle);
        
        // 自动创建或关联用户
        vehicleUserSyncService.syncVehicleUser(savedVehicle);
        
        return savedVehicle;
    }

    /**
     * 根据ID获取车辆
     * @param id 车辆ID
     * @return 车辆信息
     */
    public Optional<Vehicle> getVehicleById(String id) {
        return vehicleRepository.findById(id);
    }

    /**
     * 根据VIN码获取车辆
     * @param vin VIN码
     * @return 车辆信息
     */
    public Optional<Vehicle> getVehicleByVin(String vin) {
        return vehicleRepository.findByVin(vin);
    }

    /**
     * 根据车牌号获取车辆
     * @param licensePlate 车牌号
     * @return 车辆信息
     */
    public Optional<Vehicle> getVehicleByLicensePlate(String licensePlate) {
        return vehicleRepository.findByLicensePlate(licensePlate);
    }

    /**
     * 获取所有车辆
     * @return 车辆列表
     */
    public List<Vehicle> getAllVehicles() {
        return vehicleRepository.findAll();
    }

    /**
     * 更新车辆信息
     * @param id 车辆ID
     * @param updatedVehicle 更新的车辆信息
     * @return 更新后的车辆
     */
    @Transactional
    public Vehicle updateVehicle(String id, Vehicle updatedVehicle) {
        Vehicle existingVehicle = vehicleRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("车辆不存在: " + id));
        
        // 检查VIN码的唯一性（如果修改了VIN码）
        if (!existingVehicle.getVin().equals(updatedVehicle.getVin()) && 
            vehicleRepository.existsByVin(updatedVehicle.getVin())) {
            throw new RuntimeException("VIN码已存在: " + updatedVehicle.getVin());
        }
        
        // 检查车牌号的唯一性（如果修改了车牌号）
        if (!existingVehicle.getLicensePlate().equals(updatedVehicle.getLicensePlate()) && 
            vehicleRepository.existsByLicensePlate(updatedVehicle.getLicensePlate())) {
            throw new RuntimeException("车牌号已存在: " + updatedVehicle.getLicensePlate());
        }
        
        // 更新字段
        existingVehicle.setVin(updatedVehicle.getVin());
        existingVehicle.setLicensePlate(updatedVehicle.getLicensePlate());
        existingVehicle.setBrand(updatedVehicle.getBrand());
        existingVehicle.setModel(updatedVehicle.getModel());
        existingVehicle.setColor(updatedVehicle.getColor());
        existingVehicle.setYear(updatedVehicle.getYear());
        existingVehicle.setFuelType(updatedVehicle.getFuelType());
        existingVehicle.setTransmissionType(updatedVehicle.getTransmissionType());
        existingVehicle.setEngineCapacity(updatedVehicle.getEngineCapacity());
        existingVehicle.setVehicleType(updatedVehicle.getVehicleType());
        existingVehicle.setOwnerName(updatedVehicle.getOwnerName());
        existingVehicle.setOwnerPhone(updatedVehicle.getOwnerPhone());
        existingVehicle.setOwnerEmail(updatedVehicle.getOwnerEmail());
        existingVehicle.setRegistrationDate(updatedVehicle.getRegistrationDate());
        existingVehicle.setInsuranceExpiry(updatedVehicle.getInsuranceExpiry());
        existingVehicle.setLastMaintenance(updatedVehicle.getLastMaintenance());
        existingVehicle.setNextMaintenanceDate(updatedVehicle.getNextMaintenanceDate());
        existingVehicle.setMileage(updatedVehicle.getMileage());
        existingVehicle.setDeviceId(updatedVehicle.getDeviceId());
        existingVehicle.setDeviceSerialNumber(updatedVehicle.getDeviceSerialNumber());
        existingVehicle.setDeviceModel(updatedVehicle.getDeviceModel());
        existingVehicle.setDeviceVersion(updatedVehicle.getDeviceVersion());
        existingVehicle.setStatus(updatedVehicle.getStatus());
        existingVehicle.setIsActive(updatedVehicle.getIsActive());
        existingVehicle.setIsStolen(updatedVehicle.getIsStolen());
        existingVehicle.setNotes(updatedVehicle.getNotes());
        existingVehicle.setTags(updatedVehicle.getTags());
        existingVehicle.setAuthorizedUsers(updatedVehicle.getAuthorizedUsers());
        existingVehicle.setUpdatedAt(LocalDateTime.now());
        
        return vehicleRepository.save(existingVehicle);
    }

    /**
     * 删除车辆
     * @param id 车辆ID
     */
    public void deleteVehicle(String id) {
        if (!vehicleRepository.existsById(id)) {
            throw new RuntimeException("车辆不存在: " + id);
        }
        vehicleRepository.deleteById(id);
    }

    /**
     * 绑定车辆到用户
     * @param vehicleId 车辆ID
     * @param userId 用户ID
     * @return 更新后的车辆
     */
    @Transactional
    public Vehicle bindVehicleToUser(String vehicleId, String userId) {
        Vehicle vehicle = vehicleRepository.findById(vehicleId)
                .orElseThrow(() -> new RuntimeException("车辆不存在: " + vehicleId));
        
        User user = userService.getUserById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在: " + userId));
        
        // 设置车主信息
        vehicle.setOwnerId(userId);
        vehicle.setOwnerName(user.getFirstName() + " " + user.getLastName());
        vehicle.setOwnerEmail(user.getEmail());
        
        // 将用户添加到授权用户列表
        if (vehicle.getAuthorizedUsers() == null || !vehicle.getAuthorizedUsers().contains(userId)) {
            if (vehicle.getAuthorizedUsers() == null) {
                vehicle.setAuthorizedUsers(List.of(userId));
            } else {
                vehicle.getAuthorizedUsers().add(userId);
            }
        }
        
        vehicle.setUpdatedAt(LocalDateTime.now());
        return vehicleRepository.save(vehicle);
    }

    /**
     * 解绑车辆与用户的关联
     * @param vehicleId 车辆ID
     * @param userId 用户ID
     * @return 更新后的车辆
     */
    @Transactional
    public Vehicle unbindVehicleFromUser(String vehicleId, String userId) {
        Vehicle vehicle = vehicleRepository.findById(vehicleId)
                .orElseThrow(() -> new RuntimeException("车辆不存在: " + vehicleId));
        
        // 清除车主信息
        if (vehicle.getOwnerId() != null && vehicle.getOwnerId().equals(userId)) {
            vehicle.setOwnerId(null);
            vehicle.setOwnerName(null);
            vehicle.setOwnerEmail(null);
            vehicle.setOwnerPhone(null);
        }
        
        // 从授权用户列表中移除
        if (vehicle.getAuthorizedUsers() != null) {
            vehicle.getAuthorizedUsers().remove(userId);
        }
        
        vehicle.setUpdatedAt(LocalDateTime.now());
        return vehicleRepository.save(vehicle);
    }

    /**
     * 获取用户拥有的车辆
     * @param userId 用户ID
     * @return 车辆列表
     */
    public List<Vehicle> getVehiclesByOwner(String userId) {
        return vehicleRepository.findByOwnerId(userId);
    }

    /**
     * 获取用户有权限访问的车辆
     * @param userId 用户ID
     * @return 车辆列表
     */
    public List<Vehicle> getUserAccessibleVehicles(String userId) {
        return vehicleRepository.findByAuthorizedUsersContaining(userId);
    }

    /**
     * 检查用户是否有权限访问车辆
     * @param userId 用户ID
     * @param vehicleId 车辆ID
     * @return 是否有权限
     */
    public boolean hasAccessToVehicle(String userId, String vehicleId) {
        // 检查参数有效性
        if (userId == null || vehicleId == null || userId.isEmpty() || vehicleId.isEmpty()) {
            return false;
        }
        
        Optional<Vehicle> vehicleOptional = vehicleRepository.findById(vehicleId);
        
        // 如果车辆不存在，返回false
        if (!vehicleOptional.isPresent()) {
            return false;
        }
        
        Vehicle vehicle = vehicleOptional.get();
        
        // 检查是否为车主 (添加额外的null检查和字符串比较)
        if (vehicle.getOwnerId() != null && userId != null && vehicle.getOwnerId().trim().equals(userId.trim())) {
            return true;
        }
        
        // 检查是否在授权用户列表中
        if (vehicle.getAuthorizedUsers() != null && !vehicle.getAuthorizedUsers().isEmpty() && 
            vehicle.getAuthorizedUsers().contains(userId)) {
            return true;
        }
        
        // 检查用户的车辆ID列表中是否包含该车辆ID
        try {
            Optional<User> userOptional = userService.getUserById(userId);
            if (userOptional.isPresent()) {
                User user = userOptional.get();
                if (user.getVehicleIds() != null && !user.getVehicleIds().isEmpty() && 
                    user.getVehicleIds().contains(vehicleId)) {
                    return true;
                }
            }
        } catch (Exception e) {
            // 处理可能的异常，但不影响主要流程
        }
        
        // 添加额外的权限检查：通过ownerEmail匹配
        if (vehicle.getOwnerEmail() != null) {
            try {
                Optional<User> userOptional = userService.getUserById(userId);
                if (userOptional.isPresent() && userOptional.get().getEmail() != null && 
                    userOptional.get().getEmail().equals(vehicle.getOwnerEmail())) {
                    return true;
                }
            } catch (Exception e) {
                // 处理可能的异常，但不影响主要流程
            }
        }
        
        return false;
    }

    /**
     * 标记车辆为被盗
     * @param vehicleId 车辆ID
     * @return 更新后的车辆
     */
    public Vehicle markVehicleAsStolen(String vehicleId) {
        Vehicle vehicle = vehicleRepository.findById(vehicleId)
                .orElseThrow(() -> new RuntimeException("车辆不存在: " + vehicleId));
        
        vehicle.setIsStolen(true);
        vehicle.setStatus(Vehicle.Status.STOLEN.name());
        vehicle.setUpdatedAt(LocalDateTime.now());
        
        return vehicleRepository.save(vehicle);
    }

    /**
     * 取消车辆被盗标记
     * @param vehicleId 车辆ID
     * @return 更新后的车辆
     */
    public Vehicle unmarkVehicleAsStolen(String vehicleId) {
        Vehicle vehicle = vehicleRepository.findById(vehicleId)
                .orElseThrow(() -> new RuntimeException("车辆不存在: " + vehicleId));
        
        vehicle.setIsStolen(false);
        vehicle.setStatus(Vehicle.Status.ACTIVE.name());
        vehicle.setUpdatedAt(LocalDateTime.now());
        
        return vehicleRepository.save(vehicle);
    }

    /**
     * 更新车辆最后位置
     * @param vehicleId 车辆ID
     * @param latitude 纬度
     * @param longitude 经度
     * @return 更新后的车辆
     */
    public Vehicle updateVehicleLocation(String vehicleId, double latitude, double longitude) {
        Vehicle vehicle = vehicleRepository.findById(vehicleId)
                .orElseThrow(() -> new RuntimeException("车辆不存在: " + vehicleId));
        
        vehicle.setLastLatitude(latitude);
        vehicle.setLastLongitude(longitude);
        vehicle.setLastLocationUpdate(LocalDateTime.now());
        vehicle.setUpdatedAt(LocalDateTime.now());
        
        return vehicleRepository.save(vehicle);
    }

    /**
     * 根据品牌获取车辆
     * @param brand 品牌
     * @return 车辆列表
     */
    public List<Vehicle> getVehiclesByBrand(String brand) {
        return vehicleRepository.findByBrand(brand);
    }

    /**
     * 根据状态获取车辆
     * @param status 状态
     * @return 车辆列表
     */
    public List<Vehicle> getVehiclesByStatus(String status) {
        return vehicleRepository.findByStatus(status);
    }

    /**
     * 搜索车辆
     * @param keyword 搜索关键词（品牌、型号、车牌号等）
     * @return 车辆列表
     */
    public List<Vehicle> searchVehicles(String keyword) {
        // 这里可以实现更复杂的搜索逻辑
        // 暂时实现简单的搜索
        return vehicleRepository.findAll().stream()
                .filter(v -> keyword == null || keyword.isEmpty() ||
                        (v.getBrand() != null && v.getBrand().toLowerCase().contains(keyword.toLowerCase())) ||
                        (v.getModel() != null && v.getModel().toLowerCase().contains(keyword.toLowerCase())) ||
                        (v.getLicensePlate() != null && v.getLicensePlate().toLowerCase().contains(keyword.toLowerCase())) ||
                        (v.getVin() != null && v.getVin().toLowerCase().contains(keyword.toLowerCase())))
                .toList();
    }
}